// Real-time File Monitor WebSocket Client
// 这个文件展示如何在前端接收实时图片监控通知

class RealtimeFileMonitor {
    constructor() {
        this.websocket = null;
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        this.reconnectInterval = 3000;
    }

    // 连接WebSocket
    connect() {
        try {
            // 根据项目的WebSocket配置调整URL
            const wsUrl = `ws://${window.location.host}/websocket`;
            this.websocket = new WebSocket(wsUrl);
            
            this.websocket.onopen = this.onOpen.bind(this);
            this.websocket.onmessage = this.onMessage.bind(this);
            this.websocket.onclose = this.onClose.bind(this);
            this.websocket.onerror = this.onError.bind(this);
        } catch (error) {
            console.error('WebSocket连接失败:', error);
            this.handleReconnect();
        }
    }

    onOpen(event) {
        console.log('WebSocket连接已建立');
        this.reconnectAttempts = 0;
        
        // 发送认证信息（如果需要）
        this.sendAuthMessage();
    }

    onMessage(event) {
        try {
            const message = JSON.parse(event.data);
            this.handleMessage(message);
        } catch (error) {
            console.error('解析WebSocket消息失败:', error);
        }
    }

    onClose(event) {
        console.log('WebSocket连接已关闭:', event.code, event.reason);
        this.handleReconnect();
    }

    onError(error) {
        console.error('WebSocket错误:', error);
    }

    // 处理接收到的消息
    handleMessage(message) {
        if (message.channel === 'SYSTEM_NOTICE' && message.data) {
            const data = message.data;
            
            switch (data.type) {
                case 'NEW_IMAGE_DETECTED':
                    this.handleNewImageDetected(data);
                    break;
                case 'DUPLICATE_IMAGE_SKIPPED':
                    this.handleDuplicateImageSkipped(data);
                    break;
                case 'FILE_PROCESS_ERROR':
                    this.handleFileProcessError(data);
                    break;
                case 'MONITOR_STATUS_CHANGE':
                    this.handleMonitorStatusChange(data);
                    break;
                case 'MONITOR_STATISTICS':
                    this.handleMonitorStatistics(data);
                    break;
                default:
                    console.log('未知消息类型:', data.type);
            }
        }
    }

    // 处理新图片检测通知
    handleNewImageDetected(data) {
        console.log('检测到新图片:', data);
        
        // 显示通知
        this.showNotification('success', '新图片检测', data.message);
        
        // 更新UI
        this.updateImageList(data);
        
        // 播放提示音（可选）
        this.playNotificationSound();
    }

    // 处理重复图片跳过通知
    handleDuplicateImageSkipped(data) {
        console.log('跳过重复图片:', data);
        this.showNotification('warning', '重复图片', data.message);
    }

    // 处理文件处理错误通知
    handleFileProcessError(data) {
        console.error('文件处理错误:', data);
        this.showNotification('error', '处理错误', data.message);
    }

    // 处理监控状态变更通知
    handleMonitorStatusChange(data) {
        console.log('监控状态变更:', data);
        this.showNotification('info', '监控状态', data.message);
        this.updateMonitorStatus(data);
    }

    // 处理监控统计信息通知
    handleMonitorStatistics(data) {
        console.log('监控统计:', data);
        this.updateStatistics(data);
    }

    // 显示通知
    showNotification(type, title, message) {
        // 这里可以集成具体的通知组件，如Element Plus的ElNotification
        console.log(`[${type.toUpperCase()}] ${title}: ${message}`);
        
        // 示例：使用浏览器原生通知
        if ('Notification' in window && Notification.permission === 'granted') {
            new Notification(title, {
                body: message,
                icon: '/favicon.ico'
            });
        }
    }

    // 更新图片列表
    updateImageList(data) {
        // 添加新检测到的图片到列表
        const imageItem = {
            id: Date.now(),
            originalFilename: data.originalFilename,
            newFilename: data.newFilename,
            fileUrl: data.fileUrl,
            fileSize: data.fileSize,
            fileType: data.fileType,
            processTime: data.processTime,
            monitorId: data.monitorId
        };
        
        // 触发Vue组件更新或直接操作DOM
        this.addImageToDisplay(imageItem);
    }

    // 更新监控状态
    updateMonitorStatus(data) {
        // 更新监控状态显示
        const monitorElement = document.querySelector(`[data-monitor-id="${data.monitorId}"]`);
        if (monitorElement) {
            monitorElement.className = `monitor-status ${data.status.toLowerCase()}`;
            monitorElement.textContent = data.status;
        }
    }

    // 更新统计信息
    updateStatistics(data) {
        // 更新统计数据显示
        document.querySelector('#total-files').textContent = data.totalFiles;
        document.querySelector('#success-files').textContent = data.successFiles;
        document.querySelector('#error-files').textContent = data.errorFiles;
        document.querySelector('#success-rate').textContent = `${data.successRate.toFixed(1)}%`;
    }

    // 添加图片到显示列表
    addImageToDisplay(imageItem) {
        // 创建图片显示元素
        const imageElement = document.createElement('div');
        imageElement.className = 'image-item';
        imageElement.innerHTML = `
            <div class="image-info">
                <h4>${imageItem.originalFilename}</h4>
                <p>处理时间: ${imageItem.processTime}</p>
                <p>文件大小: ${this.formatFileSize(imageItem.fileSize)}</p>
                <p>文件类型: ${imageItem.fileType}</p>
            </div>
            <div class="image-preview">
                <img src="${imageItem.fileUrl}" alt="${imageItem.originalFilename}" 
                     style="max-width: 200px; max-height: 150px;">
            </div>
        `;
        
        // 添加到页面顶部
        const container = document.querySelector('#image-list');
        if (container) {
            container.insertBefore(imageElement, container.firstChild);
        }
    }

    // 格式化文件大小
    formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    // 播放通知声音
    playNotificationSound() {
        const audio = new Audio('/notification.mp3');
        audio.volume = 0.3;
        audio.play().catch(e => console.log('无法播放通知声音:', e));
    }

    // 发送认证消息
    sendAuthMessage() {
        // 根据项目的认证方式发送认证信息
        const token = localStorage.getItem('token') || sessionStorage.getItem('token');
        if (token) {
            this.websocket.send(JSON.stringify({
                type: 'auth',
                token: token
            }));
        }
    }

    // 处理重连
    handleReconnect() {
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectAttempts++;
            console.log(`尝试重连... (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
            setTimeout(() => this.connect(), this.reconnectInterval);
        } else {
            console.error('WebSocket重连失败，已达到最大重连次数');
        }
    }

    // 断开连接
    disconnect() {
        if (this.websocket) {
            this.websocket.close();
            this.websocket = null;
        }
    }
}

// 使用示例
const fileMonitor = new RealtimeFileMonitor();

// 页面加载时连接
document.addEventListener('DOMContentLoaded', () => {
    // 请求通知权限
    if ('Notification' in window) {
        Notification.requestPermission();
    }
    
    // 连接WebSocket
    fileMonitor.connect();
});

// 页面卸载时断开连接
window.addEventListener('beforeunload', () => {
    fileMonitor.disconnect();
});

export default RealtimeFileMonitor;